import { createServer, Command, logger, LogLevelOptions, ModeOptions, dynamicImport } from 'f2e-server3'
import { app_serve } from './actions'
import { createMiddleRBAC, createServiceFile } from 'f2e-middle-rbac'
import fs from 'node:fs'
import path from 'node:path'

const { version } = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), { encoding: 'utf-8' }))

const command = new Command('f2e-react-app')
command.version(version)
command
    .option('-m, --mode <mode>', 'server mode: dev/prod/build', 'prod', ModeOptions)
    .option('-p, --port <port>', 'server port', 2850)
    .option('-l, --level <level>', 'log level: DEBUG/INFO/WARN/ERROR,', 'INFO', LogLevelOptions)
    .action(async ({ port, mode, level }) => {
        logger.setLevel(level)
        const service = createServiceFile({})
        let TailwindPlugin;
        if (mode != 'prod') {
            TailwindPlugin = await dynamicImport('@tailwindcss/postcss')
        }
        createServer({
            mode,
            port,
            gzip: true,
            try_files: "index.html",
            buildFilter: (pathname) => /^(css(\/index|$)|static|index|favicon)/.test(pathname),
            watchFilter: (pathname) => /^(css|src|index|favicon)/.test(pathname),
            proxies: [
                { location: '/f2e-server', origin: 'https://gitee.com/' }
            ],
            auth: {
                redirect: true,
                store: service.userService,
            },
            postcss: TailwindPlugin && {
                entryPoints: {
                    in: 'src/main.css',
                    out: 'static/main.css',
                },
                plugins: [
                    TailwindPlugin({
                        optimize: mode === 'build',
                    }),
                ],
            },
            middlewares: [
                createMiddleRBAC(service, { logout_url: '/logout' }),
                app_serve,
            ],
        })
    })

command.parse(process.argv)
